package com.ruoyi.wzgl.wzck.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.echarts.EChartsBt;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.ejkgl.ejkwz.domain.Ejkwz;
import com.ruoyi.ejkgl.ejkwz.service.IEjkwzService;
import com.ruoyi.wzgl.wzck.domain.Wzck;
import com.ruoyi.wzgl.wzck.domain.WzckCkmx;
import com.ruoyi.wzgl.wzck.service.IWzckService;
import com.ruoyi.wzgl.wzck.vo.WzCkTopVo;
import com.ruoyi.wzgl.wzxx.domain.Wzxx;
import com.ruoyi.wzgl.wzxx.service.IWzxxService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 物资出库Controller
 *
 * @author huacai
 * @date 2024-09-25
 */
@RestController
@RequestMapping("/wzgl/wzck")
public class WzckController extends BaseController {
    @Resource
    private IWzckService wzckService;

    @Resource
    private IWzxxService wzxxService;

    /**
     * 查询物资出库列表
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzck:list')")
    @GetMapping("/list")
    public TableDataInfo list(Wzck wzck) {
        startPage();
        List<Wzck> list = wzckService.selectWzckList(wzck);
        return getDataTable(list);
    }

    /**
     * 导出物资出库列表
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzck:export')")
    @Log(title = "物资出库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Wzck wzck) {
        List<Wzck> list = wzckService.selectWzckList(wzck);
        List<Wzck> resultList = new ArrayList<>();
        for (Wzck item : list) {
            Wzck result = wzckService.selectWzckByWzckId(item.getWzckId());
            result.setWzckCkmxList(result.getWzckCkmxList()); // 设置查询到的子表数据到主表对象中
            resultList.add(result); // 将查询结果添加到结果集合中
        }
        ExcelUtil<Wzck> util = new ExcelUtil<Wzck>(Wzck.class);
        util.exportExcel(response, resultList, "物资出库数据");
    }

    /**
     * 下载模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Wzck> util = new ExcelUtil<Wzck>(Wzck.class);
        util.importTemplateExcel(response, "物资出库数据");
    }

    /**
     * 导入数据
     */
    @Log(title = "物资出库", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('wzgl:wzck:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<Wzck> util = new ExcelUtil<Wzck>(Wzck.class);
        InputStream inputStream = file.getInputStream();
        List<Wzck> list = util.importExcel(inputStream);
        inputStream.close();
        int count = wzckService.batchInsertWzck(list);
        return AjaxResult.success("导入成功" + count + "条信息！");
    }

    /**
     * 获取物资出库详细信息
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzck:query')")
    @GetMapping(value = "/{wzckId}")
    public AjaxResult getInfo(@PathVariable("wzckId") Integer wzckId) {
        return success(wzckService.selectWzckByWzckId(wzckId));
    }

    /**
     * 新增物资出库
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzck:add')")
    @Log(title = "物资出库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Wzck wzck) {
        wzck.setUserId(Math.toIntExact(getUserId()));
        wzck.setDeptId(Math.toIntExact(getDeptId()));
        wzck.setCreateBy(getUsername());

        return toAjax(wzckService.insertWzck(wzck));
    }

    /**
     * 报废出库
     */
    @Log(title = "报废出库", businessType = BusinessType.INSERT)
    @PostMapping("/insertBfCk")
    public AjaxResult insertBfCk(@RequestBody Wzck wzck) {
        wzck.setUserId(Math.toIntExact(getUserId()));
        wzck.setDeptId(Math.toIntExact(getDeptId()));
        wzck.setCreateBy(getUsername());
        wzck.setCkZt("报废完成");

        //获取出库明细List
        List<WzckCkmx> wzckCkmxList = wzck.getWzckCkmxList();
        //遍历出库明细
        for (WzckCkmx wzckCkmx : wzckCkmxList) {
            Integer wzxxId = wzckCkmx.getWzxxId(); //物资ID
            Integer ckSl = wzckCkmx.getCkSl(); //出库数量
            //根据出库明细中的物资ID 查询 物资基本信息表中的 物资详情
            Wzxx wzxxBySelect = wzxxService.selectWzxxByWzxxId(wzxxId);
            Integer kc = wzxxBySelect.getKc(); //该物资的库存

            //new一个 物资信息 实体类
            Wzxx wzxx = new Wzxx();
            wzxx.setWzxxId(wzxxId); //插入物资ID
            wzxx.setKc(kc - ckSl); //库存减出库数量
            wzxxService.updateWzxx(wzxx); //调用物资Service的更新方法
        }

        return toAjax(wzckService.insertBfCk(wzck));
    }

    /**
     * 个人领用出库
     */
    @Log(title = "个人领用出库", businessType = BusinessType.INSERT)
    @PostMapping("/insertGrLyCk")
    public AjaxResult insertGrLyCk(@RequestBody Wzck wzck) {
        wzck.setUserId(Math.toIntExact(getUserId()));
        wzck.setDeptId(Math.toIntExact(getDeptId()));
        wzck.setCreateBy(getUsername());
        wzck.setCkZt("领用完成");

        //获取出库明细List
        List<WzckCkmx> wzckCkmxList = wzck.getWzckCkmxList();
        //遍历出库明细
        for (WzckCkmx wzckCkmx : wzckCkmxList) {
            Integer wzxxId = wzckCkmx.getWzxxId(); //物资ID
            Integer ckSl = wzckCkmx.getCkSl(); //出库数量
            //根据出库明细中的物资ID 查询 物资基本信息表中的 物资详情
            Wzxx wzxxBySelect = wzxxService.selectWzxxByWzxxId(wzxxId);
            Integer kc = wzxxBySelect.getKc(); //该物资的库存

            //new一个 物资信息 实体类
            Wzxx wzxx = new Wzxx();
            wzxx.setWzxxId(wzxxId); //插入物资ID
            wzxx.setKc(kc - ckSl); //库存减出库数量
            wzxxService.updateWzxx(wzxx); //调用物资Service的更新方法
        }

        return toAjax(wzckService.insertGrLyCk(wzck));
    }

    /**
     * 修改物资出库
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzck:edit')")
    @Log(title = "物资出库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Wzck wzck) {
        return toAjax(wzckService.updateWzck(wzck));
    }

    @Resource
    private IEjkwzService ejkwzService; //二级库物资Service

    /**
     * 确定出库
     */
    @Log(title = "确定出库", businessType = BusinessType.UPDATE)
    @PutMapping("/qdck")
    @Transactional
    public AjaxResult updateQdck(@RequestBody Wzck wzck) {
        //物资出库ID
        Integer wzckId = wzck.getWzckId();
        //根据这条出库单的 出库ID 查询主子表数据
        Wzck wzckRe = wzckService.selectWzckByWzckId(wzckId);
        //出库物资明细
        List<WzckCkmx> wzckCkmxList = wzckRe.getWzckCkmxList();
        for (WzckCkmx wzckCkmx : wzckCkmxList) {
            Integer wzxxId = wzckCkmx.getWzxxId();
            Integer ckSl = wzckCkmx.getCkSl(); //出库数量
            Wzxx wzxx = wzxxService.selectWzxxByWzxxId(wzxxId);
            Integer kc = wzxx.getKc(); //库存
            if (ckSl > kc) { //出库数量大于库存
                return error(wzckCkmx.getWzName() + "的出库数量大于当前库存 请检查!!");
            }
        }
        //代表所有物资的出库数量都小于等于库存
        for (WzckCkmx wzckCkmx : wzckCkmxList) {
            Integer wzxxId = wzckCkmx.getWzxxId();
            Integer ckSl = wzckCkmx.getCkSl(); //出库数量
            Wzxx wzxx = wzxxService.selectWzxxByWzxxId(wzxxId);
            Integer kc = wzxx.getKc(); //库存
            Wzxx wzxxUp = new Wzxx();
            wzxxUp.setWzxxId(wzxxId);
            wzxxUp.setKc(kc - ckSl);
            wzxxService.updateWzxx(wzxxUp);
        }
        for (WzckCkmx wzckCkmx : wzckCkmxList) {
            //查询二级库物资列表存不存在某个wzxx_id(物资信息ID) 和工区
            String sf = ejkwzService.selectCzEjkwzId(wzckCkmx.getWzxxId(), wzck.getGq());
            Ejkwz ejkwz = new Ejkwz();
            if (sf.equals("false")) { //二级库物资表中没有这个物资ID
                ejkwz.setEjkwzId(IdUtils.fastSimpleUUID()); //主键UUID
                ejkwz.setGq(wzck.getGq()); //工区
                ejkwz.setWzxxId(wzckCkmx.getWzxxId()); //物资信息ID
                ejkwz.setKc(wzckCkmx.getCkSl()); //库存 (把出库明细中这个物资的出库数量插入)
                ejkwzService.insertEjkwz(ejkwz); //调用二级库物资的新增方法
            } else if (sf.equals("true")) { //二级库物资表中有这个物资ID
                //根据物资ID和工区查询二级库物资的这条信息
                Ejkwz ejkwzByWzxxId = ejkwzService.selectEjkwzByWzxxId(wzckCkmx.getWzxxId(), wzck.getGq());
                ejkwz.setEjkwzId(ejkwzByWzxxId.getEjkwzId());
                ejkwz.setGq(wzck.getGq()); //工区
                ejkwz.setWzxxId(wzckCkmx.getWzxxId()); //物资信息ID
                ejkwz.setKc(ejkwzByWzxxId.getKc() + wzckCkmx.getCkSl()); //库存 (本来有的库存) 加上 (把出库明细中这个物资的出库数量插入)
                ejkwzService.updateEjkwz(ejkwz); //调用二级库物资的修改方法
            }

        }

        return toAjax(wzckService.updateQdck(wzck));
//        return toAjax(1);
    }

    /**
     * 删除物资出库
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzck:remove')")
    @Log(title = "物资出库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{wzckIds}")
    public AjaxResult remove(@PathVariable Integer[] wzckIds) {
        return toAjax(wzckService.deleteWzckByWzckIds(wzckIds));
    }

    /**
     * 一级库物资出库Top10
     */
    @GetMapping("/getWzCkTop")
    public AjaxResult getWzCkTop() {
        List<EChartsBt> result = new ArrayList<>();

        List<WzCkTopVo> wzCkTopVos = wzckService.getWzCkTop();
        for (WzCkTopVo wzCkTopVo : wzCkTopVos) {
            EChartsBt eChartsBt = new EChartsBt();
            eChartsBt.setName(wzCkTopVo.getWzName());
            eChartsBt.setValue(wzCkTopVo.getCkSl());
            result.add(eChartsBt);
        }

        return success(result);
    }

}
